package com.fjb.tool.bio.block;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Description:多人聊天 bio多线程客户端
 * @author hemiao
 * @time:2020年4月17日 下午2:08:33
 */
public class ImThreadBioClient {
	
	/**
	 * 默认地址
	 */
	private String DEFAULT_LOCATION = "127.0.0.1";
		
	/**
	 * 默认端口
	 */
	private int DEFAULT_PROT = 8088;
	
	/**
	 * 退出
	 */
	private String QUIT = "quit";
	
	private Socket socket;
	
	private BufferedReader reader;
	
	private BufferedWriter writer;
	
	// 启动
	public void start() {
		try {
			socket = new Socket(DEFAULT_LOCATION,DEFAULT_PROT);
			System.out.println(" 客户端启动成功.... ");
			// 输入
			InputStream inputStream = socket.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream));

			// 输出
			OutputStream outputStream = socket.getOutputStream();
			writer = new BufferedWriter(new OutputStreamWriter(outputStream));
				
			// 创建一个线程  等待用户输入
			new Thread(()->{
				// 创建一个 用户等待输入流
				BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
				System.out.println(" 等待用户输入...... Port = "+socket.getPort());
				// 等待用户输入
				while (true) {	
					try {
						// 用户输入的信息  
						String consoleReadLine = consoleReader.readLine();
						// 发送信息
						if(consoleReadLine!=null) {
							writer.write(consoleReadLine + "\n");
							writer.flush();
							
							// 判断用户是否退出
							if(consoleReadLine.equals(QUIT)) {
								System.out.println(" 用户退出 ");
								break;
							}
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
			
			// 监听 读取服务端发送的消息
			String serverReadLine = null;		
			while((serverReadLine = reader.readLine())!=null) {
				System.out.println(" 服务端转发 收到-->： "+serverReadLine);
			}		
			System.out.println("客户端  监听服务端发送的消息  --> reader.readLine()是一个阻塞函数  关掉流 才会执行这个 ");
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {	
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {

		ImThreadBioClient imThreadBioClient = new ImThreadBioClient();
		imThreadBioClient.start();
	}
	
}
